//
//  Log.swift
//  
//
//  Created by bo wang on 2020/8/8.
//  Copyright © 2020 wangbo. All rights reserved.
//

import Foundation
import CocoaLumberjack

fileprivate class FileLoggerFormatter: NSObject, DDLogFormatter {
    
    lazy var dateFormatter: DateFormatter = {
        let ins = DateFormatter()
        ins.formatterBehavior = .behavior10_4
        ins.locale = Locale(identifier: "en_US_POSIX")
        ins.dateFormat = "yyyy-MM-dd HH:mm:ss:SSS"
        return ins
    }()
    
    func format(message logMessage: DDLogMessage) -> String? {
        let time = dateFormatter.string(from: logMessage.timestamp)
        let file = (logMessage.file as NSString).lastPathComponent
//        let `func` = logMessage.function ?? "_"
        let line = "#\(logMessage.line)"
        let tag = "[" + safe_string(logMessage.representedObject, default: LogTag.default.rawValue) + "]"
        return "👉" + time + "\t" + file + "\t" + line + "\t" + tag + "\t" + logMessage.message
//        return "📝👇 " + time + " | " + file + " | " + `func` + " | #" + line + " | " + tag + "\n" + logMessage.message
    }
}

class FileLogger: DDFileLogger {
    
    static let shared: FileLogger = {
        let ins = FileLogger()
        // 每天一个日志文件
        ins.rollingFrequency = 60 * 60 * 24 * 1
        // 不限制日志文件大小
        ins.maximumFileSize = 0
        // 日志文件的最大数量。某天产生了日志，将创建一个日志文件。一共可以创建30个。
        // 但是也有可能是上传日志时强制滚动了日志文件
        ins.logFileManager.maximumNumberOfLogFiles = 30
        ins.logFormatter = FileLoggerFormatter()

        let dir = ins.logFileManager.logsDirectory
        print("Start file logger. Files dir: \(dir)")
        
        return ins
    }()
    
    override func log(message logMessage: DDLogMessage) {
        super.log(message: logMessage)
        
        if Log.enableLogPanel {
//            DispatchQueue.main.async {
//                LogPanel.shared.log(logMessage.message)
//            }
        }
    }
}

struct Log {
    private let placeholder: Int = 0
    
    private static let shared: Log = {
        DDLog.add(FileLogger.shared)
        DDLog.add(DDOSLogger.sharedInstance)
        return Log()
    }()
    
    private init() {}
    
    /// 是否启用日志面板
    static var enableLogPanel = true
    
    /// 存放日志文件的文件夹
    static var logFileDir: String { FileLogger.shared.logFileManager.logsDirectory }
    
    static func debug(tag: LogTag = .default,
                      _ logs: String?,
                      file: StaticString = #file,
                      function: StaticString = #function,
                      line: UInt = #line) {
        guard let str = logs else { return }
        _ = Self.shared
        let content = tag.rawValue + " - " + str
        DDLogDebug(content, file: file, function: function, line: line, tag: tag.rawValue)
    }
    
    static func info(tag: LogTag = .default,
                     _ logs: String?,
                     file: StaticString = #file,
                     function: StaticString = #function,
                     line: UInt = #line) {
        guard let str = logs else { return }
        _ = Self.shared
        let content = tag.rawValue + " - " + str
        DDLogInfo(content, file: file, function: function, line: line, tag: tag.rawValue)
    }
    
    static func warn(tag: LogTag = .default,
                     _ logs: String?,
                     file: StaticString = #file,
                     function: StaticString = #function,
                     line: UInt = #line) {
        guard let str = logs else { return }
        _ = Self.shared
        let content = tag.rawValue + " - " + "⚠️" + str + "⚠️"
        DDLogWarn(content, file: file, function: function, line: line, tag: tag.rawValue)
    }
    
    static func error(tag: LogTag = .default,
                      _ logs: String?,
                      file: StaticString = #file,
                      function: StaticString = #function,
                      line: UInt = #line) {
        guard let str = logs else { return }
        _ = Self.shared
        let content = tag.rawValue + " - " + "❌" + str + "❌"
        DDLogError(content, file: file, function: function, line: line, tag: tag.rawValue)
    }
}
